package com.xdb.presistence.kv;

import java.util.HashMap;
import java.util.Map;

import com.xdb.exception.XDBRuntimeException;
import com.xdb.presistence.metadata.TableMetadata;
/**
 * 表注册中心
 * @author woate
 *
 */
public final class TableRegister {
	final Map<String, Map<String, String>> tables = new HashMap<String, Map<String,String>>();
	final Map<String, TableMetadata> tableMetadatas = new HashMap<String, TableMetadata>();
	/**
	 * 绑定表
	 * @param name
	 * @param table
	 */
	public void bind(TableMetadata metadata, Map<String, String> table){
		if(table == null){
			throw new NullPointerException("TABLE ["+ metadata.getName()+"] bind Map is null!");
		}
		if(metadata == null){
			throw new NullPointerException("TABLE metadata is null!");
		}
		if(tables.containsKey(metadata.getName())){
			throw new XDBRuntimeException("TABLE ["+ metadata.getName()+"] is already exist!");
		}
		tableMetadatas.put(metadata.getName(), metadata);
		tables.put(metadata.getName(), table);
	}
	/**
	 * 解绑表
	 * @param name
	 * @return
	 */
	public Map<String, String> unbind(String name){
		vlidata(name);
		Map<String, String> table = tables.get(name);
		tableMetadatas.remove(name);
		tables.remove(name);
		return table;
	}
	/**
	 * 按照表名查找表对象
	 * @param name
	 * @return
	 */
	public Map<String, String> lookup(String name){
		vlidata(name);
		Map<String, String> table = tables.get(name);
		return table;
	}
	
	public TableMetadata lookupMetadata(String name){
		vlidata(name);
		TableMetadata metadata = tableMetadatas.get(name);
		return metadata;
	}
	private void vlidata(String name) {
		if(name == null || name.isEmpty()){
			throw new NullPointerException("TABLE name is null!");
		}
		if(!tables.containsKey(name)){
			throw new XDBRuntimeException("TABLE ["+ name+"] is not exist!");
		}
	}
}
